<?php
/*
 * Страница со списком регионов
 */

class multitender_action_by_region extends multitender_action {

    function run() {

        include $this->conf['basedir'] . '/regions.php';

        $this->conf['page_title'] = 'Закупки по регионам';

        $tpl = $this->new_tpl();
        $tpl->caching = TRuE;
        $tpl->cache_lifetime = mt_rand(45, 70) * 59;

        if( $tpl->is_cached('by_region.tpl') ) {
            return $tpl->fetch('by_region.tpl');
        }

        $data = multitender_model_data_common::singleton()->get_data();

        $rcnt = $this->db->GetAll("SELECT region_id, COUNT(id) as count FROM item WHERE date_end > NOW() GROUP BY region_id");
        foreach ($rcnt as $r) { $arr[$r['region_id']] = $r['count']; }

        foreach ($data['region'] as $region) {
            $region['count'] = isset($arr[$region['id']]) ? (int)$arr[$region['id']] : 0;
            $region['link'] = isset($regions_chpu[$region['id']]) ? $regions_chpu[$region['id']] : 'region/?region_id='.$region['id'];

            $contry_id = Ceil($region['id'] / 100);
            
            if ($region['id'] % 100==0) {
                $contry[$contry_id]['info'] = $region;
                continue;
            }

            $firstletter = mb_substr($region['name'], 0, 1, 'utf-8');
            $group = 0;
            if (preg_match("#республика#sui", $region['name'])) {
                if (preg_match("#республика ([A-я]{1})#sui", $region['name'], $fl)) {
                    $firstletter = $fl[1];
                }
                if ($contry_id==1) {
                    $group=1;
                    $region['name'] = trim(preg_replace("#республика#siu", "", $region['name']));
                }
                
            }

            $contry[$contry_id][$group][$firstletter][] = $region;
        }

        ksort($contry);

        for ($i=1; $i<=count($contry); $i++) {
            foreach ($contry[$i] as $key => $group) {
                $s = 0;
                foreach ($group as $letter) { $s += count($letter);  }
                ksort($group);
                $contry[$i][$key] = $group;
                $contry[$i][$key]['heightcolumn'] = Ceil($s / 3)-1;
            }
        }
        $tpl->assign('base_url', $this->conf['pref']['link_base']);
        $tpl->assign('contries', $contry);
        return $tpl->fetch('by_region.tpl');

        $this->conf['page']['description']  = 'Госзакупки по регионам';
        $this->conf['page']['title']        = 'Госзакупки по регионам';

        $generator = $this->new_action('region_view');

        $tpl->assign('list', $generator->run('region'));

        return $tpl->fetch('by_region.tpl');

    } //function run

}

